import { ChangeDetectorRef, Component, EventEmitter, Inject, Input, OnChanges, Optional, Output, SimpleChanges } from "@angular/core";
import { Options } from 'sortablejs';
import { MonkFormDesignConfig, MONK_FORMDEISGN_CONFIG } from "../../monk-form-design.interface";
import { NzContextMenuService, NzDropdownMenuComponent } from "ng-zorro-antd/dropdown";
import { NzNotificationService } from "ng-zorro-antd/notification";

@Component({
  selector: 'app-layout-item',
  templateUrl: './layout-item.component.html',
  styleUrls: ['./layout-item.component.scss']
})
export class LayoutItemComponent implements OnChanges {
  @Input() record: any;
  @Input() config: any;
  @Input() selectItem: any;
  @Input() startType: string;
  @Input() insertAllowedType: string[]

  @Output() readonly handleColAdd: EventEmitter<any> = new EventEmitter();
  @Output() readonly handleSelectItem = new EventEmitter();
  @Output() readonly handleCopy = new EventEmitter();
  @Output() readonly handleDelete = new EventEmitter();
  private contextData: {
    record: any
  } & Record<'tdIndex'|'trIndex', number>

  get insertAllowed() {
    return this.insertAllowedType.includes(this.startType);
  }
  _cahce: {[key: string]: Options} = {
  }

  constructor(
    @Optional() @Inject(MONK_FORMDEISGN_CONFIG) public formDesignConfig: MonkFormDesignConfig,
    private cdf: ChangeDetectorRef,
    private nzContextMenuService: NzContextMenuService,
    private nzNotificationService: NzNotificationService,
  ) {
  }
  ngOnChanges(changes: SimpleChanges): void {
    console.log()
  }

  ///needAllowed: 表格需要限制能拖拽进入的组件类型
  genOptions(colItem, index, needAllowed = false) {
    if (!this._cahce[index]) {
      this._cahce[index] = 
      {
        group: 'draggable-box',
        handle: '.drag-move',
        onAdd: (evt) => {
          this.cdf.markForCheck()
          this.onDrop({
            evt, columns: colItem.list
          })
        } 
      }
    }
    const options = this._cahce[index]
    if (needAllowed) {
      if (this.insertAllowed) {
        options.group = 'draggable-box'
      } else {
        options.group = ''
      }
      return {
        ...options
      }
    } else {
      return {
        ...options
      }
    }
  }

  onDrop(evt) {
    //debugger
    this.handleColAdd.emit(
      evt, 
    )
  }

  onDragDrop($event) {
    //this.itemDrop.emit($event)
  }

  handleCopyFn($event: Event) {
    $event.stopPropagation()
    this.cdf.markForCheck()
    this.handleCopy.emit()
  }  
  handleDeleteFn($event: Event) {
    $event.stopPropagation()
    this.cdf.markForCheck()
    this.handleDelete.emit()
  }

  handleFormNodeDelete($event) {
    this.cdf.markForCheck()
    this.handleDelete.emit($event)
  }

  handleSelectItemAndStop($event) {
    $event.stopPropagation()
    this.cdf.markForCheck()
    this.handleSelectItem.emit(this.record)
  }

  hiddenDelete() {
    if ([//"batch",
    //"card",
    "tabs",
    "grid",
    'collapse',
    ].includes(this.record.type)) {
      return this.record.columns.some(col => col.list.length > 0)
    } else if (
      ['batch', 'card', 'block'].includes(this.record.type)) {
      return this.record.list.length > 0
    } else if (this.record.type == 'table') {
      return false
    } else {
      return this.formDesignConfig?.fixedField
    }
  }

  tableContextMenu($event: MouseEvent, menu: NzDropdownMenuComponent, record: any, trIndex: number, tdIndex: number): void {
    this.nzContextMenuService.create($event, menu);
    this.contextData = {
      record, tdIndex, trIndex
    }
  }

  handleDownMerge() {
    // 向下合并

    // 判断当前行是否是最后一行，最后一行无法向下合并
    if (
      this.contextData.record.trs.length -
        this.contextData.record.trs[this.contextData.trIndex].tds[this.contextData.tdIndex]
          .rowspan <=
      this.contextData.trIndex
    ) {
      this.nzNotificationService.error('提示',"当前是最后一行，无法向下合并");
      return false;
    }

    // 获取当前单元格的rowspan
    const currentRowspan = this.contextData.record.trs[this.contextData.trIndex].tds[
      this.contextData.tdIndex
    ].rowspan;

    // 判断下一列单元格与当前单元格的colspan是否一致，如果不一致则无法合并
    if (
      this.contextData.record.trs[this.contextData.trIndex].tds[this.contextData.tdIndex]
        .colspan !==
      this.contextData.record.trs[this.contextData.trIndex + currentRowspan].tds[
        this.contextData.tdIndex
      ].colspan
    ) {
      this.nzNotificationService.error('提示',"当前表格无法向下合并");
      return false;
    }

    // 获取下一列单元格的rowspan
    const nextRowSpan = this.contextData.record.trs[
      this.contextData.trIndex + currentRowspan
    ].tds[this.contextData.tdIndex].rowspan;

    // 当前单元格rowspan等于当前单元格rowspan加上下一列单元格rowspan
    this.contextData.record.trs[this.contextData.trIndex].tds[this.contextData.tdIndex].rowspan =
      currentRowspan + nextRowSpan;

    // 将被合并的单元rowspan修改为0
    this.contextData.record.trs[this.contextData.trIndex + currentRowspan].tds[
      this.contextData.tdIndex
    ].rowspan = 0;

    // 清空被合并单元格list
    this.contextData.record.trs[this.contextData.trIndex + currentRowspan].tds[
      this.contextData.tdIndex
    ].list = [];
    this.cdf.markForCheck()
  }
  handleRightMerge() {
    // 向右合并
    // 获取当前列的所有colspan总和
    const sumCols = this.contextData.record.trs[this.contextData.trIndex].tds
      .map(item => item.colspan)
      .reduce(function(partial, value) {
        return partial + value;
      });

    // 判断是否是最后一列，最后一列无法继续向右合并
    if (
      sumCols -
        this.contextData.record.trs[this.contextData.trIndex].tds[this.contextData.tdIndex]
          .colspan <=
      this.contextData.tdIndex
    ) {
      this.nzNotificationService.error('提示',"当前是最后一列，无法向右合并");
      return false;
    }

    // 获取当前单元格的colspan
    const currentColspan = this.contextData.record.trs[this.contextData.trIndex].tds[
      this.contextData.tdIndex
    ].colspan;

    // 判断需要合并的单元格rowspan是否与当前单元格一致
    if (
      this.contextData.record.trs[this.contextData.trIndex].tds[this.contextData.tdIndex]
        .rowspan !==
      this.contextData.record.trs[this.contextData.trIndex].tds[
        this.contextData.tdIndex + currentColspan
      ].rowspan
    ) {
      this.nzNotificationService.error('提示',"当前表格无法向右合并");
      return false;
    }

    // 合并单元格colspan
    this.contextData.record.trs[this.contextData.trIndex].tds[
      this.contextData.tdIndex
    ].colspan += this.contextData.record.trs[this.contextData.trIndex].tds[
      this.contextData.tdIndex + currentColspan
    ].colspan;

    // 将被合并的单元格colspan设置为0
    this.contextData.record.trs[this.contextData.trIndex].tds[
      this.contextData.tdIndex + currentColspan
    ].colspan = 0;

    // 情况被合并单元格的list
    this.contextData.record.trs[this.contextData.trIndex].tds[
      this.contextData.tdIndex + currentColspan
    ].list = [];
    this.cdf.markForCheck()
  }
  // 拆分单元格
  handleRightSplit() {
    // 获取当前单元格的colspan及rowspan
    const { colspan, rowspan } = this.contextData.record.trs[
      this.contextData.trIndex
    ].tds[this.contextData.tdIndex];

    for (
      let rowIndex = this.contextData.trIndex, rowLen = this.contextData.trIndex + rowspan;
      rowIndex < rowLen;
      rowIndex++
    ) {
      for (
        let colIndex = this.contextData.tdIndex, colLen = this.contextData.tdIndex + colspan;
        colIndex < colLen;
        colIndex++
      ) {
        if (rowIndex === this.contextData.trIndex && colIndex === this.contextData.tdIndex) continue;
        this.contextData.record.trs[rowIndex].tds.splice(colIndex, 1, {
          colspan: 1,
          rowspan: 1,
          list: []
        });
      }
    }
    // 修改当前单元格colspan、rowspan为1
    this.contextData.record.trs[this.contextData.trIndex].tds[this.contextData.tdIndex].colspan = 1;
    this.contextData.record.trs[this.contextData.trIndex].tds[this.contextData.tdIndex].rowspan = 1;
    
    this.cdf.markForCheck()
  }
  handleAddCol() {
    // 增加列

    this.contextData.record.trs.forEach(item => {
      item.tds.splice(this.contextData.tdIndex + 1, 0, {
        colspan: 1,
        rowspan: 1,
        list: []
      });
    });
    
    this.cdf.markForCheck()
  }
  handleAddRow() {
    // 增加行
    // 获取总col值
    const sumCols = this.contextData.record.trs[0].tds
      .map(item => item.colspan)
      .reduce(function(partial, value) {
        return partial + value;
      });
    const rowJson = { tds: [] };
    for (let i = 0; i < sumCols; i++) {
      rowJson.tds.push({
        colspan: 1,
        rowspan: 1,
        list: []
      });
    }

    // 取当前rowspan最大值
    let maxRowSpan = 1;
    this.contextData.record.trs[this.contextData.trIndex].tds.forEach(item => {
      if (maxRowSpan < item.rowspan) {
        maxRowSpan = item.rowspan;
      }
    });

    // 在rowspan最大值处插入数据
    this.contextData.record.trs.splice(
      this.contextData.trIndex + maxRowSpan,
      0,
      rowJson
    );
    this.cdf.markForCheck()
  }
}